package com.mk.common;

import com.mk.model.entity.JwtUser;
import com.mk.model.entity.Role;
import com.mk.model.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yanzhiping on 2017/9/4.
 */
public final class JwtUserFactory {

    private JwtUserFactory() {
    }

    public static JwtUser create(User user, List<Role> roles) {
        return new JwtUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getName(),
                mapToGrantedAuthorities(roles));
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<Role> authorities) {
        List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
        if (!CollectionUtils.isEmpty(authorities)){
            for (Role role:authorities){
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getName());
                roles.add(authority);
            }
        }
        return roles;
    }
}
